package com.gec.hrm.dao.impl;

import com.gec.hrm.pojo.Document;
import com.gec.hrm.util.JDBCUtils;

import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class DocumentDaoImpl extends JDBCUtils<Document> implements DocumentDao {
    UserDao userDao=new UserDaoImpl();

    @Override
    public List<Document> listDocument(Document doc, int page, int limit) {
        String sql="select * from document_inf where 1=1 ";
        if(doc.getTitle()!=null&&doc.getTitle()!=""){
            sql+=" and title like '%"+doc.getTitle()+"%'";
        }
        sql+=" limit ?,?";
        List<Document> documents = query(sql,(page-1)*limit,limit);
        return documents;
    }

    @Override
    public int addDocument(Document document) {
        return update("insert into document_inf  values(null,?,?,?,?,?,current_timestamp,?)",
                document.getTitle(),document.getFileName(),
                document.getFileType(),document.getFileUrl(),document.getRemark(),
                document.getUserId()
                );
    }

    @Override
    public int delDocument(int id) {
        return update("delete from document_inf where id=?",id);
    }

    @Override
    public int updDocument(Document document) {
        return update("update document_inf set title=?,remark=?,filename=?," +
                        "filetype=?,filebytes=? where id=?",
                document.getTitle(),document.getRemark(),document.getFileName(),
                document.getFileType(),document.getFileUrl(),document.getId());
    }

    @Override
    public int count() {
        return query("select * from document_inf").size();
    }

    @Override
    public Document findById(int id) {
        return query("select * from document_inf where id=?",id).get(0);
    }


    @Override
    public Document getBean(ResultSet rs) {
        Document document=new Document();
        try {
            document.setId(rs.getInt("id"));
            document.setTitle(rs.getString("title"));
            document.setFileName(rs.getString("filename"));
            document.setFileType(rs.getString("filetype"));
            document.setFileUrl(rs.getString("filebytes"));
            document.setRemark(rs.getString("remark"));
            document.setCreateDate(rs.getDate("create_date"));
            document.setUserId(rs.getInt("user_id"));
            document.setUserName(userDao.findById(document.getUserId()).getLoginname());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return document;
    }
}
